layui.define(['engine_form', 'form', 'http', 'public', 'drawer'], function (exports) {
    let STR_FORMDESIGN = 'DesignForm';
    let ARR_CONFIG = {
        findData: [],
        title: '',
        modeid: 0,
        menu_id: 0,
        type: 0,
        state: null,
        current: {},
        index: [],           // 组件分类索引
        itemIndex: {},       // 子组件元素索引
        master: undefined,   // 主界面拖拽实例
    };
    let GetConfig = function () {
        return ARR_CONFIG;
    }
    let ChangeType = function (index = 0) {
        ARR_CONFIG.type = index;
    }
    let Init = function (modeid = '') {
        ARR_CONFIG.modeid = layui.public.GetQuery('id') || 0;
        if (modeid) {
            ARR_CONFIG.modeid = modeid;
        }
        let URL = '?id=' + ARR_CONFIG.modeid;
        history.pushState(null, null, URL);
        layui.http.SendAjax('/ruinuo/design.lists/index', {modeid: ARR_CONFIG.modeid}, [], function (res) {
            let data = res.data || [];
            InitData['source'] = data.source || [];
            InitData['detail'] = data.detail || {};
            layui.public.ViewTpl(data, 'view_body_data', 'view_body');
            $(".design-tab ul li").eq(ARR_CONFIG.type).click();
            ARR_CONFIG.title = data['title'] || '';
            if (data['mode_id']) {
                $('.design_head .title').html('列表设计器<i class="layui-icon layui-icon-right"></i><strong style="color: var(--theme_color);">' + data['title'] + '</strong>');
                TableColsView();
                TableButtonView();
                TablePowerView();
                TableTabView();
                ChangeSelect('style');
                ChangeSelect('left_type');
                layui.form.on('select(d_select_filter)', function (data) {
                    let elem = data.elem;
                    let field = $(elem).attr('name');
                    ChangeSelect(field);
                })
            } else {
                ARR_CONFIG.modeid = 0;
                history.pushState(null, null, '?id=0');
            }
            if (modeid == '') {
                ModeList();
            }
        })
    };


    let ModeList = function () {
        layui.http.SendAjax('/ruinuo/design.form/modelist', [], [], function (res) {
            let data = res.data || [];
            layui.public.ViewTpl(data, 'view_mode_list_data', 'view_mode_list');
        })
    }
    let ClickMenu = function () {
        let menu_id = ARR_CONFIG.menu_id;
        let modeid = ARR_CONFIG.modeid;
        let click = '';
        let elem = '';
        $('.design-left .layui-menu ul li').each(function (b) {
            if ($(this).attr('data-id') == menu_id) {
                click = $(this);
                elem = $(this).parent('ul').parent('.layui-menu-item-group');
            }
        })
        if (click == "") {
            click = $('.design-left .layui-menu ul li').eq(0);
            elem = $('.design-left .layui-menu .layui-menu-item-group');
        }
        $(click).click();
        $(elem).attr('class', 'layui-menu-item-group layui-menu-item-down');
        $(elem).find("i").attr('class', 'layui-icon layui-icon-up');
    }

    let TableFind = function (menu_id = '') {
        ARR_CONFIG.menu_id = menu_id;
        Design();
    }

    let TableColsView = function () {

        let tableid = 'table_view_1';
        let data = InitData.detail.table_cols || [];
        $("#focus_view_1").val(JSON.stringify(data));
        let title = '<div class="pear-btn pear-btn-smm btn_theme_1" onclick="layui.design_table.AddTable()">新增</div>';
        let tpl = '<div>' +
            '<button type="button" class="pear-btn pear-btn-danger pear-btn-smm" onclick="layui.engine_table.DeleteTable(\'table_view_1\',{{d.LAY_INDEX}})"><i class="layui-icon layui-icon-delete"></i></button>' +
            '<button type="button" class="pear-btn pear-btn-primary pear-btn-smm ruinuo-drag"><i class="layui-icon layui-icon-slider"></i></button>' +
            '</div>';
        let muban = '<div>' +
            '<div  class="pear-btn pear-btn-primary pear-btn-smm" onclick="layui.design_table.BindTpl(this)">配置</div>' +
            '</div>'
        let cols = [
            {title: title, tpl: tpl, minWidth: 110},
            {field: 'field', title: '字段编码', minWidth: 140},
            {field: 'title', title: '字段名称', minWidth: 140, update: 'input'},
            {field: 'width', title: '宽', minWidth: 90, update: 'input'},
            {field: 'group', title: '分组名称', minWidth: 90, update: 'input'},
            {field: 'update', title: '编辑', minWidth: 90, update: 'select', options: 'edit'},
            {field: 'align', title: '对齐', minWidth: 90, update: 'select', options: 'position'},
            {field: 'options', title: '数据源', minWidth: 140, update: 'select', options: 'select'},
            {field: 'search', title: '搜索配置', minWidth: 140, update: 'select', options: 'search'},
            {field: 'show_rule', title: '显示规则', minWidth: 90, update: 'input',hide:1},
            {field: 'hide', title: '隐藏', minWidth: 75, update: 'switch'},
            {field: 'count', title: '合计', minWidth: 75, update: 'switch'},
            {field: 'sort', title: '排序', minWidth: 75, update: 'switch'},
            {field: 'tpl', title: '显示', minWidth: 90, fixed: 'right', tpl: muban},
        ];
        let table = {
            style: 1,
            elem: tableid,
            limit: 0,
            page: false,
            height:'full-200',
            source: InitData.source || [],
            cols: layui.engine_table.ColsAll(cols, tableid),
        }
        SettingData[tableid] = table;
        layui.engine_table.TableStyle(table, data);
        FieldChecked(InitData.detail.table_field);
    }

    let TableButtonView = function () {
        let tableid = 'table_view_2';
        let data = InitData.detail.table_button || [];
        let parent_id = InitData.detail.menu_id || '';
        $("#focus_view_2").val(JSON.stringify(data));
        let url = '/admin/menu/add/?elem=table_view_2&type=3&parent_id=' + parent_id;
        let title = '<div class="pear-btn pear-btn-smm btn_theme_1" onclick="layui.public.OpenWindow(\'' + url + '\',\'新增\',700);">新增</div>';
        let tpl = '<div>';
        tpl += '{{#  if(d.is_sync==1){ }}';
        tpl += '<button class="pear-btn pear-btn-smm btn_theme_1" onclick="layui.design_table.TableButtonCurd(2,\'{{d.id}}\')"><i class="ruinuo-icon icon-edit" title="修改"></i></button>';
        tpl += '<button class="pear-btn pear-btn-smm btn_theme_2" onclick="layui.design_table.TableButtonCurd(3,\'{{d.id}}\')"><i class="ruinuo-icon icon-ashbin" title="删除" ></i></button>';
        tpl += '{{#  } else { }}';
        tpl += '<div class="pear-btn pear-btn-primary pear-btn-smm" onclick="layui.design_table.TableButtonCurd(1,{{d.LAY_INDEX}})">同步</div>';
        tpl += '{{#  } }}';
        tpl += '</div>';
        let cols = [
            {title: title, tpl: tpl, width: 110},
            {field: 'title', title: '按钮名称', width: 120},
            {field: 'is_sync', title: '同步到菜单', width: 120, options: 'yesno'},
            {field: 'position', title: '按钮位置', width: 120, options: 'button_position'},
            {field: 'href', title: '访问路径'},
            {field: 'power_node', title: '授权标识'},
            {field: 'open_type', title: '打开方式', width: 120, options: 'button_type'},
            {field: 'status', title: '是否启用', width: 120, options: 'yesno'},
        ];
        let table = {
            style: 1,
            elem: tableid,
            limit: 0,
            page: false,
            height:'full-200',
            source: InitData.source || [],
            cols: layui.engine_table.ColsAll(cols, tableid),
        }
        SettingData[tableid] = table;
        layui.engine_table.TableStyle(table, data);
    }

    let TableButtonCurd = function (type = 1, index = 0) {
        switch (Number(type)) {
            case 1:
                let parent_id = InitData.detail.menu_id || '';
                let table_button = InitData.detail.table_button || [];
                let button = table_button[index];
                let sort = index + 1;
                let data = 'icon=' + button['icon'] + '&title=' + button['title'] + '&parent_id=' + parent_id + '&type=3&position=' + button['position'] + '';
                data += '&sort=' + sort + '&open_type=' + button['open_type'] + '&href=' + button['href'] + '&power_node=' + button['power_node'] + '&btn_class=' + button['btn_class'];
                layui.public.OpenWindow('/admin/menu/add/?elem=table_view_2&' + data, '同步按钮', 700);
                break;
            case 2:
                layui.public.OpenWindow('/admin/menu/edit/?elem=table_view_2&id=' + index, '修改', 700);
                break;
            case 3:
                let tableelem = 'table_view_2';
                layui.public.OpenAjax('/admin/menu/delete/?id=' + index, '刪除', "layui.design_table.Init();");
                break;
        }
    }

    let TablePowerView = function () {
        layui.engine_form.BindSelect('power_user', 'select', 'power_user', 'user_list', 1);
        layui.engine_form.BindSelect('power_role', 'select', 'power_role', 'role_list', 1);
        layui.engine_form.BindSelect('power_department', 'select', 'power_department', 'department_list', 1);
        let tableid = 'table_view_3';
        let power = InitData.detail.table_power || [];
        let data = power.power_field || [];
        $("#focus_view_3").val(JSON.stringify(data));
        let title = '<div class="pear-btn pear-btn-smm btn_theme_1" onclick="layui.engine_table.AddTable(\'table_view_3\')">新增</div>';
        let tpl = '<div>' +
            '<button type="button" class="pear-btn pear-btn-danger pear-btn-smm" onclick="layui.engine_table.DeleteTable(\'table_view_3\',{{d.LAY_INDEX}})"><i class="layui-icon layui-icon-delete"></i></button>' +
            '<button type="button" class="pear-btn pear-btn-primary pear-btn-smm ruinuo-drag"><i class="layui-icon layui-icon-slider"></i></button>' +
            '</div>';
        let cols = [
            {width: 110, title: title, tpl: tpl},
            {field: 'field', title: '权限字段', update: 'select', options: 'table_field'},
            {field: 'is_path', title: '允许上级查看', update: 'switch'},
        ];
        let table = {
            style: 1,
            elem: tableid,
            limit: 0,
            page: false,
            source: InitData.source || [],
            cols: layui.engine_table.ColsAll(cols, tableid),
        }
        SettingData[tableid] = table;
        layui.engine_table.TableStyle(table, data);


    }

    let TableTabView = function () {

        let tableid = 'table_view_4';
        let data = InitData.detail.table_tab || [];
        $("#focus_view_4").val(JSON.stringify(data));
        let title = '<div class="pear-btn pear-btn-smm btn_theme_1" onclick="layui.engine_table.AddTable(\'table_view_4\')">新增</div>';
        let tpl = '<div>' +
            '<button type="button" class="pear-btn pear-btn-danger pear-btn-smm" onclick="layui.engine_table.DeleteTable(\'table_view_4\',{{d.LAY_INDEX}})"><i class="layui-icon layui-icon-delete"></i></button>' +
            '<button type="button" class="pear-btn pear-btn-primary pear-btn-smm ruinuo-drag"><i class="layui-icon layui-icon-slider"></i></button>' +
            '</div>';
        let cols = [
            {width: 110, title: title, tpl: tpl},
            {field: 'name', title: '名称', update: 'input'},
            {field: 'rule', title: '数据规则', update: 'input'},
        ];
        let table = {
            style: 1,
            elem: tableid,
            limit: 0,
            page: false,
            source: InitData.source || [],
            cols: layui.engine_table.ColsAll(cols, tableid),
        }
        SettingData[tableid] = table;
        layui.engine_table.TableStyle(table, data);
    }


    let OpenAdd = function (type = 1) {
        let modeid = ARR_CONFIG.modeid || 0;
        if (modeid == 0) {
            layer.msg('请先选择模块', {icon: 2});
            layui.public.DrawerTpl('.mode_list', '300px', '模块类别');
            return false;
        }
        let url = '/ruinuo/lists/add/?mode_id=' + ARR_CONFIG.modeid;
        layui.public.OpenWindow(url, '新增菜单')
    }

    let AddTable = function () {
        var type = ARR_CONFIG.type || 1;
        switch (type) {
            case 1:
                layui.public.DrawerTpl('.field-layer-right', '400px', '模块类别')
                break;
            case 2:
                break;
            case 3:
                break;
        }
    }
    let FieldChecked = function (list = []) {

        let FiledStr = '';
        let table_filed_html = "";
        for (let i = 0; i < list.length; i++) {
            table_filed_html += '<tr>';
            table_filed_html += '<td colspan="3"><strong>' + list[i].value + '(' + list[i].label + ')</strong></td>';
            table_filed_html += '</tr>';
            let child = list[i].children;
            for (let ii = 0; ii < child.length; ii++) {
                let checked = '';
                if (child[ii].on) {
                    checked = 'checked';
                }
                table_filed_html += '<tr>';
                table_filed_html += '<td align="right"><input name="table_field_name" class="field_val_' + child[ii].value + '"  type="checkbox" ' + checked + ' data-name="' + child[ii].label + '" value="' + child[ii].value + '" lay-filter="table_field" lay-skin="primary"></td>';
                table_filed_html += '<td align="left">' + child[ii].value + '</td>';
                table_filed_html += '<td align="left">' + child[ii].label + '</td>';
                table_filed_html += '</tr>';
            }
        }
        $(".layui-table-filed  tbody").html(table_filed_html);
        layui.form.render();
        layui.form.on('checkbox(table_field)', function (data) {
            let checked = 2;
            if (data.elem.checked) {
                checked = 1;
            }
            let post = {
                id: ARR_CONFIG.modeid,
                type: ARR_CONFIG.type,
                num: data.value || '',
                title: $(data.elem).attr('data-name') || '',
                checked: checked
            }
            layui.http.SendAjax('/ruinuo/design.lists/colsadd', post, [], function (res) {
                layui.table.reload('table_view_1', {
                    data: res.data, url: '',
                })
                TplCustom();
                layui.form.render();
            })
        });
    }
    let EditCols = function (arr) {
        let post = {
            id: ARR_CONFIG.modeid,
            type: ARR_CONFIG.type,
            item: JSON.stringify(arr),
        }
        layui.http.SendAjax('/ruinuo/design.lists/editcols', post, [], function (res) {
            if (res.code != 200) {
                layer.msg(res.msg, {icon: 2});

            } else {
                layer.msg('修改成功', {icon: 1});
                TplCustom();
                $("input[name='table_field_name']").prop("checked", false);
                arr.forEach(item => {
                    $(".field_val_" + item.field).prop("checked", true);
                })
                layui.form.render();
            }

        })
    }
    let BindTpl = function (obj) {
        let table = layui.table.getRowData(obj);
        ARR_CONFIG.current = table.data || {};
        let title=ARR_CONFIG.current.field+"("+ARR_CONFIG.current.title+")"+'模板配置';
        ;
        let area = ['800px', '600px'];
        let content = '/common/component/listtpl';
        let that = '';
        layer.open({
            type: 2,
            offset: 'auto',
            title: title,
            area: area,
            scrollbar: true,
            content: content,
            btnAlign: 'r',
            btn: ['确定', '取消'],
            shade: 0.3,
            yes: function (index) {
                let iframe = window['layui-layer-iframe' + index];
                let datas = iframe.SendForm() || {};
                let tpl=datas.tpl || '';
                let show_rule=datas.show_rule || '';
                table.data['tpl'] = tpl;
                table.data['show_rule'] = show_rule;
                let dataBak = layui.table.cache['table_view_1'];
                EditCols(dataBak);
                let bindex = layer.getFrameIndex('layui-layer-iframe' + index);
                layer.close(bindex);
            }
        })
    }

    let SaveSubmit = function (type) {
        let modeid = ARR_CONFIG.modeid || 0;
        if (modeid == 0) {
            layer.msg('请先选择模块', {icon: 2});
            layui.public.DrawerTpl('.mode_list', '300px', '模块类别');
            return false;
        }


        let detail = InitData.detail || [];
        let postData = layui.engine_form.GetFormData(detail);
        postData['app_num'] = detail.app_num || '';
        postData['mode_num'] = detail.mode_num || '';
        postData['menu_id'] = detail.menu_id || '';
        if (postData['style'] == 3) {
            if (postData['tree_field'] == '') {
                Formfocus('树形字段不能为空', 'tree_field')
                return;
            }
            if (postData['tree_name'] == '') {
                Formfocus('树形名称不能为空', 'tree_name')
                return;
            }
        }
        if (postData['asc_desc'] == '') {
            Formfocus('排序设置不能为空', 'asc_desc')
            return;
        }
        if (postData['page_num'] == '') {
            Formfocus('分页设置不能为空', 'page_num')
            return;
        }
        let table_power = postData.table_power || '[]';
        table_power = eval(table_power);
        if (table_power.length > 0) {
            let field_num = '';
            let is_yz = 2;
            table_power.forEach((item, index) => {
                let field = item.field || '';
                if (field == '' && is_yz == 2) {
                    field_num = index;
                    is_yz = 1;
                }
            })
            if (is_yz == 1) {
                $(".design-tab ul li").eq(2).click();
                Formfocus('权限字段不能为空', 'field', field_num)
                return;
            }
        }
        let table_tab = postData.table_tab || '[]';
        table_tab = eval(table_tab);
        if (table_tab.length > 0) {
            let tab_field_num = '';
            let tab_field_name = '';
            let tab_field_msg = '';
            let tab_field_ok = 2;
            table_tab.forEach((item, index) => {
                let name = item.name || '';
                if (name == '' && tab_field_ok == 2) {
                    tab_field_num = index;
                    tab_field_name = 'name';
                    tab_field_msg = 'TAB菜单名称必须填写';
                    tab_field_ok = 1;
                }
                let rule = item.rule || '';
                if (rule == '' && tab_field_ok == 2) {
                    tab_field_num = index;
                    tab_field_name = 'rule';
                    tab_field_msg = 'TAB菜单数据规则必须填写';
                    tab_field_ok = 1;
                }
            })
            if (tab_field_ok == 1) {
                $(".design-tab ul li").eq(3).click();
                Formfocus(tab_field_msg, tab_field_name, tab_field_num)
                return;
            }
        }


        if (postData['is_left'] == 1) {
            if (postData['left_title'] == '') {
                $(".design-tab ul li").eq(4).click();
                Formfocus('左侧标题不能为空', 'left_title')
                return;
            }
            if (postData['left_type'] == '') {
                $(".design-tab ul li").eq(4).click();
                Formfocus('左侧关联方式不能为空', 'left_type')
                return;
            }
            if (postData['left_type'] == 1 && postData['left_options'] == '') {
                $(".design-tab ul li").eq(4).click();
                Formfocus('左侧关联数据源不能为空', 'left_options')
                return;
            }
            if (postData['left_type'] == 2 && postData['left_mode'] == '') {
                $(".design-tab ul li").eq(4).click();
                Formfocus('左侧关联模块不能为空', 'left_options')
                return;
            }
            if (postData['left_key_field'] == '') {
                $(".design-tab ul li").eq(4).click();
                Formfocus('左侧主键字段不能为空', 'left_key_field')
                return;
            }
            if (postData['left_show_field'] == '') {
                $(".design-tab ul li").eq(4).click();
                Formfocus('左侧显示字段不能为空', 'left_show_field')
                return;
            }
            if (postData['left_field'] == '') {
                $(".design-tab ul li").eq(4).click();
                Formfocus('左侧关联字段不能为空', 'left_field')
                return;
            }
        }

        postData.table_power = JSON.stringify(table_power);
        postData.table_tab = JSON.stringify(table_tab);

        let table_button = postData.table_button || [];
        postData.table_button = JSON.stringify(table_button);

        let table_field = postData.table_field || [];
        postData.table_field = JSON.stringify(table_field);

        let table_cols = postData.table_cols || [];
        postData.table_cols = JSON.stringify(table_cols);
        let SendData = {mode_id: modeid, mode_name: ARR_CONFIG.title};
        $.each(postData, function (field, value) {
            if (field != 'table_button' && field != 'table_field' && field != 'table_cols') {
                SendData[field] = value;
            }
        })


        switch (Number(type)) {
            case 1://保存
                layui.http.SendAjax('/ruinuo/design.lists/edit/', SendData, [], function (res) {
                    if (res.code == 200) {
                        layer.msg('保存成功', {icon: 1});
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                })
                break;
            case 2://预览
                let detail=InitData.detail || {};
                let url="/"+detail['app_num']+"/"+detail['mode_num']+"/index/";
                layui.public.OpenWindow(url,'预览');
                break;
            case 3://生成
                break;
        }
    }
    let TplCustom = function () {
        let style = $("select[name='style']").val() || '';
        let arr=layui.table.cache['table_view_1'] || [];
        let newFields = [];
        arr.forEach(item => {
            let hide = item['hide'] || 2;
            if (hide == 2) {
                newFields.push(item);
            }
        })
        let html = '<div class="layui-card">\n';
        newFields.forEach((item, index) => {

            if (index == 0) {
                if (style == 4) {
                    html += '<div class="layui-card-header">\n';
                    html += '<div class="title">{{item.' + item['field'] + '}}</div>\n';
                    html += '</div>\n';
                }
                if (style == 5) {
                    html += '<div class="layui-card-header file_con">\n';
                    html += '<div class="file">{{item.' + item['field'] + '}}</div>\n';
                    html += '</div>\n';
                }
                html += '<div class="layui-card-body">\n';
            } else {
                html += '<ul>\n';
                html += '<ul>\n';
                html += '<li>' + item['title'] + '：</li>\n';
                html += '<li>{{item.' + item['field'] + '}}</li>\n';
                html += '</ul>\n';
                if (index+1 == arr.length) {
                    html += '</div>\n';
                }
            }
        })
        html += '</div>';
        $("textarea[name='style_tpl']").val(html)
        $(".card_table_con").html(html);
    }

    let ChangeSelect = function (field = '') {
        let value = '';
        switch (field) {
            case 'style':
                value = $("select[name='style']").val() || '';
                $(".tree_con").hide();
                $(".style_con").hide();
                if (value == 3) {
                    $(".tree_con").show();
                }
                if (value == 4 || value == 5) {
                    $(".style_con").show();
                    TplCustom();
                }
                break;

            case "left_type":
                value = $("select[name='left_type']").val() || '';
                $(".left_options_box").hide();
                $(".left_mode_box").hide();
                if (value == 1) {
                    $(".left_options_box").show();
                    $("input[name='left_key_field']").val('value');
                    $("input[name='left_show_field']").val('label');
                }
                if (value == 2) {
                    $(".left_mode_box").show();
                }
                break;
        }
    }

    let Formfocus = function (title, field, index = 0) {
        let obj = $("input[name='" + field + "'],textarea[name='" + field + "'],select[name='" + field + "']").eq(index);
        $(obj).focus();
        $(obj).addClass('layui-form-danger');
        layer.msg(title, {icon: 2});
    }


    let design_table = {
        Init: Init,//初始化
        ModeList: ModeList,//拖曳完成
        TableFind: TableFind,
        TableColsView: TableColsView,
        TableButtonView: TableButtonView,
        TableButtonCurd: TableButtonCurd,
        TablePowerView: TablePowerView,
        TableTabView: TableTabView,
        ClickMenu: ClickMenu,
        OpenAdd: OpenAdd,
        AddTable: AddTable,
        FieldChecked: FieldChecked,
        EditCols: EditCols,
        GetConfig: GetConfig,
        BindTpl: BindTpl,
        SaveSubmit: SaveSubmit,
        ChangeSelect: ChangeSelect,
        Formfocus: Formfocus,
        ChangeType: ChangeType,
        TplCustom: TplCustom
    };
    exports('design_table', design_table);
})



